from django.db import models
from hdiary.injections.models import *
from hdiary.middleware import threadlocals
from django.contrib.auth.models import User


class Reception(models.Model):
    date = models.DateField(auto_now_add = True)
    patient = models.ForeignKey(User, blank = True, default = None)
    rec_date = models.DateField('date received')
    comment = models.CharField(maxlength=100, blank=True, default=None)
  
    def sum_of_units(self):
        sum = 0
        for asr in AmpouleSeriesReception.objects.filter(reception=self.id):
            sum += int(asr.ampoule_series.units)*int(asr.amount)
        return sum

    def __unicode__(self):
        return unicode(self.rec_date)+" "+unicode(self.sum_of_units())

    def save(self):
        if self.patient_id is None:
            self.patient_id = threadlocals.get_current_user().id
        super(Reception, self).save()
    
    class Admin:
        list_display = ('rec_date', 'sum_of_units')
        list_filter = ['rec_date']
        date_hierarchy = 'rec_date'
#    a trial to clean up edit view
#    fields = (
#      (None, {'fields': ('rec_date','comment')}),
#    )

class AmpouleSeries(models.Model):
    date = models.DateField(auto_now_add = True)
  #RegisterableModel
    code = models.CharField(maxlength=25, core=True)
    units = models.IntegerField(core=True)
    def available(self):
        sum = 0
        for asr in AmpouleSeriesReception.objects.filter(ampoule_series=self.id):
            sum += asr.amount
        for asi in AmpouleSeriesInjection.objects.filter(ampoule_series=self.id):
            sum -= asi.amount
        return sum
    def __unicode__(self):
        return self.code+": "+unicode(self.units)
    class Admin:
        list_display = ('code', 'units', 'available')
        list_filter = ['units']

class AmpouleSeriesReception(models.Model):
    reception = models.ForeignKey(Reception, edit_inline=models.TABULAR)
    ampoule_series = models.ForeignKey(AmpouleSeries, core=True)
    amount = models.PositiveIntegerField(core=True)
    def __unicode__(self):
        return unicode(self.ampoule_series)+" "+unicode(self.amount)

class AmpouleSeriesInjection(models.Model):
    injection = models.ForeignKey(Injection, edit_inline=models.TABULAR)
    ampoule_series = models.ForeignKey(AmpouleSeries, core=True)
    amount = models.PositiveIntegerField(core=True)
    def __unicode__(self):
        return unicode(self.ampoule_series)+" "+unicode(self.amount)

